package io.renren.config;

import io.renren.utils.CommonResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 自定义异常信息
 * TODO 建议加上@ResponseStatus
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandle {

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldError().getField() + CommonConstant.SEPARATOR_NUMBER + e.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数校验失败:[{}]", msg);
        return new CommonResponse(ResponseCodeEnum.ILLEGAL_ARGUMENT.getCode(), msg);
    }

    @ResponseBody
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    public CommonResponse handleMethodArgumentNotValidException(MissingServletRequestParameterException e) {
        log.error("参数校验失败:[{}]", e.getParameterName());
        return new CommonResponse(ResponseCodeEnum.ILLEGAL_ARGUMENT.getCode(), ResponseCodeEnum.ILLEGAL_ARGUMENT.getMessage() + CommonConstant.SEPARATOR_NUMBER + e.getParameterName());
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = HttpMessageConversionException.class)
    public CommonResponse handleMissingServletRequestParameter(HttpMessageConversionException e) {
        log.error("参数解析异常:{}", e.getMessage());
        return new CommonResponse(ResponseCodeEnum.ILLEGAL_ARGUMENT.getCode(), "参数解析异常");
    }

    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public CommonResponse handleBusinessException(BusinessException e) {
        log.error("自定义异常:{}", e.getMessage(), e);
        return new CommonResponse(e);
    }

    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public CommonResponse handleDataAccessException(DataAccessException e) {
        log.error("数据库错误:{}", e.getMessage(), e);
        return new CommonResponse(ResponseCodeEnum.DATABASE_ERROR);

    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public CommonResponse handleException(Exception e) {
        log.error("系统异常:{}", e.getMessage(), e);
        return new CommonResponse(ResponseCodeEnum.ERROR);
    }

}
